﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Alchemy;
using System.Net;
using PServiceBus.Core.Manager;
using PServiceBus.Core.Runtime;

namespace PServiceBus.AlchemyWebSocket {
    public class AlchemyWebSocketServer : PServiceBus.Core.Interface.IWebSocketServer {
        WebSocketServer server;
        #region IWebSocketServer Members

        public void Start(string host, int port, bool secured) {
            var ipAddress = Dns.GetHostAddresses(host)
                .First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                .ToString();
            server = new WebSocketServer(port, IPAddress.Parse(ipAddress));
            server.TimeOut = TimeSpan.FromDays(30);
            server.OnConnect = x => {
                var connection = new AlchemyWebSocketConnection(x);
                OnOpen(connection);
                WebSocketConnectionManager.Register(connection);
            };
            server.OnReceive = x => OnMessage(new AlchemyWebSocketConnection(x), x.DataFrame.ToString());
            server.OnDisconnect = x =>
            {
                var connection = new AlchemyWebSocketConnection(x);
                OnClose(connection);
                WebSocketConnectionManager.Register(connection);
            }; ;
            server.Start();
        }

        public Action<Core.Interface.IWebSocketConnection, string> OnMessage { get; set; }

        public Action<Core.Interface.IWebSocketConnection, Exception> OnError { get; set; }

        public Action<Core.Interface.IWebSocketConnection> OnOpen { get; set; }

        public Action<Core.Interface.IWebSocketConnection> OnClose { get; set; }

        public string Cerfx { get; set; }

        public void Close() {
            server.Dispose();
            ShellHelper.NetShRemoveUrlAcl(server.Port);
        }

        #endregion
    }
}
